<?php

namespace app\utils;

class DataProcessor
{
    private $mappings = [];
    private $timeFields = [];

    /**
     * 设置字段映射规则
     */
    public function setMappings(array $mappings): self
    {
        $this->mappings = $mappings;
        return $this;
    }

    /**
     * 获取字段映射规则
     */
    public function getMappings(): array
    {
        return $this->mappings;
    }

    /**
     * 添加单个字段映射规则
     */
    public function addMapping(string $field, array $mapping): self
    {
        $this->mappings[$field] = $mapping;
        return $this;
    }

    /**
     * 设置时间字段
     */
    public function setTimeFields(array $timeFields): self
    {
        $this->timeFields = $timeFields;
        return $this;
    }

    /**
     * 获取时间字段
     */
    public function getTimeFields(): array
    {
        return $this->timeFields;
    }

    /**
     * 添加时间字段
     */
    public function addTimeField(string $timeField): self
    {
        $this->timeFields[] = $timeField;
        return $this;
    }

    /**
     * 处理数据
     */
    public function process(array $data, array $fields): array
    {
        $currentTime = time();

        return array_map(function($row) use ($fields, $currentTime) {
            $item = [];

            // 处理字段映射
            foreach ($fields as $index => $field) {
                $value = $row[$index] ?? null;
                $item[$field] = $this->mapFieldValue($field, $value);
            }

            // 添加时间字段
            foreach ($this->timeFields as $timeField) {
                $item[$timeField] = $currentTime;
            }

            return $item;
        }, $data);
    }

    /**
     * 字段值映射
     */
    private function mapFieldValue(string $field, $value)
    {
        return $this->mappings[$field][$value] ?? $value;
    }
}